﻿using System;
using System.Linq;
using System.Web.Security;
using System.Windows.Forms;
using ComputerVision.BaseForm;
using ComputerVision.Common;

namespace ComputerVision.Role
{
    public partial class frmSelectUser : frmDetail
    {
        private string _roleName = string.Empty;

        public frmSelectUser(string roleName)
        {
            InitializeComponent();
            _roleName = roleName;
        }

        private void frmSelectUser_Load(object sender, EventArgs e)
        {
            try
            {
                if (_roleName == null)
                {
                    AlertList.Warning("Chưa chọn nhóm người dùng");
                }
                var arrUser = Roles.GetUsersInRole(_roleName);
                var arrAllUser = Membership.GetAllUsers();
                foreach (MembershipUser user in arrAllUser)
                {
                    if (arrUser.Length == 0)
                    {
                        string[] rows = { user.UserName, user.LastActivityDate.ToShortDateString() };
                        var item = new ListViewItem(rows);
                        lstViewUser.Items.Add(item);
                    }
                    else
                    {
                        foreach (var userName in arrUser)
                        {
                            if (!user.UserName.Contains(userName))
                            {
                                string[] rows = { user.UserName, user.LastActivityDate.ToShortDateString() };
                                var item = new ListViewItem(rows);
                                lstViewUser.Items.Add(item);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                AlertList.Error(ex.Message);
            }
            
        }

        protected override void Insert()
        {
            var checkedItems = lstViewUser.CheckedItems;
            foreach (ListViewItem item in checkedItems)
            {
                try
                {
                    Roles.AddUserToRole(item.Text, _roleName);
                }
                catch (Exception ex)
                {
                    AlertList.Error("Có lỗi phát sinh trong quá trình chọn người dùng.");
                }
            }
        }
    }
}